//
//  GameService.m
//  YouthOlympic2014
//
//  Created by Li Yuhang on 14-7-1.
//  Copyright (c) 2014年 mitian. All rights reserved.
//



#import "GameService.h"

@interface GameService()
- (NSArray*/*GameEvent*/) getEventsByGameId: (NSString*)gameId
                               andSubGameId: (NSString*) subgameId
                                    andDate: (NSDate*)gameDate;

- (NSArray*/*GameEvent*/) getEventsByPlaceId: (NSString*) placeId
                               andSubPlaceId: (NSString*) supplaceId
                                     andDate:(NSDate*) gameDate;
@end


@implementation GameService



- (void) getAllGames:(CompletionBlock)completion
{
    //处理超时
    __block BOOL isResultCompletion = NO;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, RESULT_TIME_MAX * NSEC_PER_SEC);
    dispatch_after(popTime,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
        if (!isResultCompletion) {
            isResultCompletion = YES;
            NSString* errorMsg = @"timeout";
            NSError* error = [NSError errorWithDomain:errorMsg code:504 userInfo:nil];
            completion(nil,error);
        }
    });
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSError* error = nil;
        NSArray* result = nil;
        id jsonObj =  [self.api GetGameInfo:@"000000" withLan: [AppUtils getLan]];
        NSString* errorMsg = [[jsonObj objectForKey:@"ApiErrorInfo"] objectForKey:@"msg"];
        
        if (errorMsg != nil) {
            error = [NSError errorWithDomain:errorMsg code:400 userInfo:nil];
        }else{
            result =[Game instanceList:jsonObj];
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if (!isResultCompletion) {
                isResultCompletion = YES;
                completion(result,error);
            }
        });
    });

    
}

- (void) getAllSubGamesByGameId:(NSString *) gameId
                     completion:(CompletionBlock)completion
{
    //处理超时
    __block BOOL isResultCompletion = NO;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, RESULT_TIME_MAX * NSEC_PER_SEC);
    dispatch_after(popTime,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
        if (!isResultCompletion) {
            isResultCompletion = YES;
            NSString* errorMsg = @"timeout";
            NSError* error = [NSError errorWithDomain:errorMsg code:504 userInfo:nil];
            completion(nil,error);
        }
    });
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSError* error = nil;
        NSArray* result = nil;
        id jsonObj = [self.api GetGameSubTypeInfoByType:gameId withLan:[AppUtils getLan]];
        NSString* errorMsg = [[jsonObj objectForKey:@"ApiErrorInfo"] objectForKey:@"msg"];
        
        if (errorMsg != nil) {
            error = [NSError errorWithDomain:errorMsg code:400 userInfo:nil];
        }else{
            result =[SubGame instanceList:jsonObj];
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if (!isResultCompletion) {
                isResultCompletion = YES;
                completion(result,error);
            }
        });
    });
}



- (void) getGameEventsDictByGameId: (NSString*)gameId
                               andSubGameId: (NSString*) subgameId
                                    andDate: (NSString*)gameDate
                                 completion:(CompletionBlock)completion
{
    //处理超时
    __block BOOL isResultCompletion = NO;
    
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, RESULT_TIME_MAX * NSEC_PER_SEC);
    dispatch_after(popTime,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
        if (!isResultCompletion) {
            isResultCompletion = YES;
            NSString* errorMsg = @"timeout";
            NSError* error = [NSError errorWithDomain:errorMsg code:504 userInfo:nil];
            completion(nil,error);
        }
    });
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        NSError* error = nil;
        NSMutableDictionary* result = [[NSMutableDictionary alloc] init];
        NSDictionary* jsonData = [self.api GetgameDetailInfoByType:gameId andSubType:subgameId andGameDate: gameDate withLan:[AppUtils getLan]];
        NSString* errorMsg = [[jsonData objectForKey:@"ApiErrorInfo"] objectForKey:@"msg"];
        
        if (errorMsg != nil) {
            error = [NSError errorWithDomain:errorMsg code:400 userInfo:nil];
        }else{
            NSArray* jsonArr = jsonData[@"GameDetailInfo"];
            //检索数据库，查找已关注的赛事
            NSSet* staredEventIds = [self getAllStaredEventIds];
            //对数据进行加工
            for(int i=0; i<jsonArr.count; i++){
                NSMutableDictionary* item = jsonArr[i];
                NSString* timeStr = item[@"time"]; //20130816133000
                NSDictionary* timeDict = [AppUtils parseApiTimeToDictionary:timeStr];
                //
                NSString* key = [NSString stringWithFormat:@"%@:%@",(NSString*)timeDict[@"hour"],(NSString*)timeDict[@"minute"]];
                if(result[key] == nil){
                    result[key] = [[NSMutableArray alloc]init];
                }
                NSString* eventId = item[@"id"];
                item[@"stared"] = [NSNumber numberWithBool:[staredEventIds containsObject:eventId]];
                
                [result[key] addObject:[GameEvent instance:item]];
            }
            NSLog(@"result is: %@",[AppUtils replaceUnicodeDic:result]);
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if (!isResultCompletion) {
                isResultCompletion = YES;
                completion(result,error);
            }
        });
    });
}


- (void) getGameEventsDictByPlaceId: (NSString*)placeId
                               andSubPlaceId: (NSString*) subplaceId
                                     andDate:(NSString*) gameDate
                                  completion:(CompletionBlock)completion
{
    //处理超时
    __block BOOL isResultCompletion = NO;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, RESULT_TIME_MAX * NSEC_PER_SEC);
    dispatch_after(popTime,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
        if (!isResultCompletion) {
            isResultCompletion = YES;
            NSString* errorMsg = @"timeout";
            NSError* error = [NSError errorWithDomain:errorMsg code:504 userInfo:nil];
            completion(nil,error);
        }
    });
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSError* error = nil;
        NSMutableDictionary* result = [[NSMutableDictionary alloc] init];
        NSDictionary* jsonData = [self.api GetGameDetailInfoPlace:placeId andSubPlace:subplaceId andGameDate:gameDate withLan:[AppUtils getLan]];
        NSString* errorMsg = [[jsonData objectForKey:@"ApiErrorInfo"] objectForKey:@"msg"];
        
        if (errorMsg != nil) {
            error = [NSError errorWithDomain:errorMsg code:400 userInfo:nil];
        }else{
            NSArray* jsonArr = jsonData[@"GameDetailInfo"];
            //检索数据库，查找已关注的赛事
            NSSet* staredEventIds = [self getAllStaredEventIds];
            //对数据进行加工
            for(int i=0; i<jsonArr.count; i++){
                NSMutableDictionary* item = jsonArr[i];
                NSString* timeStr = item[@"time"]; //20130816133000
                NSDictionary* timeDict = [AppUtils parseApiTimeToDictionary:timeStr];
                //
                NSString* key = [NSString stringWithFormat:@"%@:%@",(NSString*)timeDict[@"hour"],(NSString*)timeDict[@"minute"]];
                if(result[key] == nil){
                    result[key] = [[NSMutableArray alloc]init];
                }
                NSString* eventId = item[@"id"];
                item[@"stared"] = [NSNumber numberWithBool:[staredEventIds containsObject:eventId]];
                
                [result[key] addObject:[GameEvent instance:item]];
            }
            NSLog(@"result is: %@",[AppUtils replaceUnicodeDic:result]);
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if (!isResultCompletion) {
                isResultCompletion = YES;
                completion(result,error);
            }
        });
    });
    
}

- (void) getGameEventsByPlaceId: (NSString*) placeId
                  andSubPlaceId: (NSString*) subplaceId
                        andDate: (NSString*) gameDate
                     completion: (CompletionBlock) completion{
    //处理超时
    __block BOOL isResultCompletion = NO;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, RESULT_TIME_MAX * NSEC_PER_SEC);
    dispatch_after(popTime,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
        if (!isResultCompletion) {
            isResultCompletion = YES;
            NSString* errorMsg = @"timeout";
            NSError* error = [NSError errorWithDomain:errorMsg code:504 userInfo:nil];
            completion(nil,error);
        }
    });
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSError* error = nil;
        NSMutableArray*/*GameEvent*/ result = [[NSMutableArray alloc] init];
        NSDictionary* jsonData = [self.api GetGameDetailInfoPlace:placeId andSubPlace:subplaceId andGameDate:gameDate withLan:[AppUtils getLan ]];
        NSString* errorMsg = [[jsonData objectForKey:@"ApiErrorInfo"] objectForKey:@"msg"];
        
        if (errorMsg != nil) {
            error = [NSError errorWithDomain:errorMsg code:400 userInfo:nil];
        }else{
            NSArray* jsonArr = jsonData[@"GameDetailInfo"];
            //对数据进行加工
            for(int i=0; i<jsonArr.count; i++){
                [result addObject:[GameEvent instance:jsonArr[i]]];
            }
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if (!isResultCompletion) {
                isResultCompletion = YES;
                completion([NSArray arrayWithArray:result],error);
            }
        });
    });
}

- (NSSet*) getAllStaredEventIds{
    FMDatabase* db = [DBUtil getDatabase];
    FMResultSet* rs = [db executeQuery:@"select ref_id from schedule order by start_date desc"];
    NSMutableSet* eventIds = [[NSMutableSet alloc]init];
    
    while ([rs next]){
        [eventIds addObject: [rs stringForColumn:@"ref_id"] ];
    }
    
    [rs close];
    [db close];
    return [NSSet setWithSet:eventIds];
}

///添加赛事到关注
- (NSInteger) addGameEventToSchedule:(GameEvent*) gameEvent{

    NSInteger day = [[gameEvent.begintime substringWithRange:NSMakeRange(6,2)] integerValue];
    
    FMDatabase* db = [DBUtil getDatabase];
    NSString *sql = [NSString stringWithFormat:@"insert into schedule(day,ref_id) values(%i,%@)",day,gameEvent.id];
    
    long result =[db executeUpdate:sql];
    NSLog(@"addGameEventToSchedule result is %ld",result);
    
    [db close];

    return result;
}

///批量添加赛事到关注
- (NSInteger) addGameEventsToSchedule:(NSArray*) gameEvents{
    FMDatabase* db = [DBUtil getDatabase];
    
    for (GameEvent *gameEvent in gameEvents) {
        NSInteger day = [[gameEvent.begintime substringWithRange:NSMakeRange(6,2)] integerValue];
        NSString *sql = [NSString stringWithFormat:@"insert into schedule(day,ref_id) values(%i,%@)",day,gameEvent.id];
        [db executeUpdate:sql];
    }
    
    [db close];
  
    return 0;
}

#pragma mark private methods
- (NSArray*/*GameEvent*/) getEventsByGameId: (NSString*)gameId andSubGameId: (NSString*) subgameId andDate: (NSDate*)gameDate{
    //TODO
    
    return nil;
}

- (NSArray*/*GameEvent*/) getEventsByPlaceId: (NSString*)placeId andSubPlaceId: (NSString*) subplaceId andDate: (NSDate*)gameDate{
    //TODO
    
    return nil;
}



@end
